package com.oasistudio.tk.connector.imp;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TreeMap;

import org.json.JSONObject;

import com.oasistudio.tk.connector.TopAPIConnectorHelper;
import com.oasistudio.tk.connector.TopApiRequest;
import com.oasistudio.tk.connector.TopApiResponse;
import com.taobao.tbw.common.TBWContext;

public class UserGetConnector implements TopAPIConnectorHelper {
	private String nick;
	private String fields="user_id,nick,alipay_account";

	public UserGetConnector() {
	}

	public void setNick(String nick){
		this.nick = nick;
	}

	public void setFields(String fields){
		this.fields = fields;
	}

	@Override
	public Object asyncPaser(byte[] part) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getApiUrl() {
		TopApiRequest request = new TopApiRequest();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		TreeMap<String, String> params = new TreeMap<String, String>();
		//系统参数
		params.put("method", "taobao.user.get");
		params.put("session", TBWContext.getInstance().getTopsession());
		params.put("timestamp", sdf.format(calendar.getTime()));
		params.put("format", "json");
		params.put("app_key", TBWContext.getInstance().getAppKey());
		params.put("v", "2.0");
		params.put("partner_id", "top-apitools");
		params.put("sign_method", "md5");
		//API method 参数
		params.put("fields", fields);
		params.put("nick", nick);
		request.params = params;
		String url = request.generalRequestUrl(true);
		System.out.println("UserGetConnector.getApiUrl() url = "+url);
		return url;
	}

	@Override
	public Object syncPaser(byte[] all) {
		UserInfo userInfo = new UserInfo();
		try {
			TopApiResponse response = new TopApiResponse("user_get_response");
			String str = new String(all, "UTF-8");
			//Log.d("return msg:", str);
			if (response.parseResult(str).success) {
				userInfo.isSuccess = true;
				JSONObject jsObj = response.data;
				if (jsObj.has("user")) {
					JSONObject userJSON = jsObj.getJSONObject("user");
					User user = new User();
					user.user_id = userJSON.optLong("user_id");
					user.nick = userJSON.optString("nick");
					user.alipay_account = userJSON.optString("alipay_account");
					user.avatar = userJSON.optString("avatar");
					if(userJSON.has("buyer_credit")){
						JSONObject buyerCredit = userJSON.getJSONObject("buyer_credit");
						user.buyer_credit = new UserCredit();
						user.buyer_credit.level = buyerCredit.optInt("level");
						user.buyer_credit.score = buyerCredit.optInt("score");
						user.buyer_credit.good_num = buyerCredit.optInt("good_num");
						user.buyer_credit.total_num = buyerCredit.optInt("total_num");
					}
					if(userJSON.has("seller_credit")){
						JSONObject sellerCredit = userJSON.getJSONObject("seller_credit");
						user.seller_credit = new UserCredit();
						user.seller_credit.level = sellerCredit.optInt("level");
						user.seller_credit.score = sellerCredit.optInt("score");
						user.seller_credit.good_num = sellerCredit.optInt("good_num");
						user.seller_credit.total_num = sellerCredit.optInt("total_num");
					}
					userInfo.user = user;
				}
			} else {
				userInfo.isSuccess = false;
				userInfo.errCode = response.errCode;
				userInfo.errInfo = response.errInfo;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userInfo;
	}

	public static class UserInfo {
		public String errCode;
		public String errInfo;
		public Boolean isSuccess;
		public User user;
	}

	public static class User {
		public Number user_id;
		public String nick;
		public String alipay_account;
		public String avatar;//头像图片地址
		public UserCredit buyer_credit;
		public UserCredit seller_credit;
		
		
		public String toString(){
			StringBuilder sb = new StringBuilder();
			sb.append("user_id:"+user_id);
			sb.append(";nick:"+nick);
			sb.append(";alipay_account:"+alipay_account);
			return sb.toString();
		}
	}
	
	public static class UserCredit{
		public Number level;//信用等级（是根据score生成的），信用等级：淘宝会员在淘宝网上的信用度，分为20个级别，级别如：level = 1 时，表示一心；level = 2 时，表示二心
		public Number score;//信用总分（“好评”加一分，“中评”不加分，“差评”扣一分。分越高，等级越高）
		public Number total_num;//收到的评价总条数。取值范围:大于零的整数
		public Number good_num;//收到的好评总条数。取值范围:大于零的整数
	}
}
